package com.teamclub.app.sservices.systemmanager

import java.util.List

import io.ebean.{Ebean, ExpressionList}
import com.teamclub.app.sforms.AppFuncTreeForm
import com.teamclub.domain.system.{AppDomainInstance, AppFuncTree, AppRole}
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.F
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.BeanUtils
import org.springframework.stereotype.Service

import scala.collection.JavaConversions._

/**
  * Created by ilkkzm on 17-8-9.
  */
@Service
class AppFuncTreeService {
  private def expr(where: ExpressionList[AppFuncTree], form: AppFuncTreeForm) {
    if(form.id != null) {
      where.eq("id", form.id)
    }
    if(form.parentId != null) {
      where.eq("parentId", form.parentId)
    }
    if(StringUtils.isNotBlank(form.appDomain)) {
      where.eq("appDomain", form.appDomain)
    }
    if(StringUtils.isNotBlank(form.organNo)) {
      val instance = Ebean.find(classOf[AppDomainInstance]).where().eq("organNo", form.organNo).findOne()
      val instanceIds = instance.getFuncTreeRef().split(",").toSet
      if(form.roleId != null) {
        val roleIds = Ebean.find(classOf[AppRole], form.roleId).getFuncTreeRef.split(",").toSet
        where.in("id", seqAsJavaList((roleIds intersect  instanceIds).toSeq))
      } else {
        where.in("id", seqAsJavaList(instanceIds.toSeq))
      }
      where.eq("appDomain", instance.getAppDomain)
    }
    where.orderBy("treeOrder asc")
  }

  def list(form: AppFuncTreeForm): F.Either[List[AppFuncTree], ErrorCode] = {
    val where = Ebean.find(classOf[AppFuncTree]).where()
    expr(where, form)
    var list = where.findList()
    F.Either.Left(list)
  }

  def add(form: AppFuncTreeForm): F.Either[AppFuncTree, ErrorCode] = {
    var instance = new AppFuncTree
    if(form.id != null) {
      instance = Ebean.find(classOf[AppFuncTree], form.id)
    }
    if(instance == null) {
      F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    } else {
      BeanUtils.copyProperties(form, instance)
      if(form.id == null) {
        instance.save()
      }else {
        instance.update()
      }
      F.Either.Left(instance)
    }
  }

  def del(form: AppFuncTreeForm): F.Either[AppFuncTree, ErrorCode] = {
    val instance = Ebean.find(classOf[AppFuncTree], form.id)
    if(instance == null) {
      F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    } else {
      instance.delete()
      F.Either.Left(instance)
    }
  }

}
